if __name__ == "__main__":
    # 初始化Flask app对象
    from app import app, db

    # 导入模块蓝图
    from UserManager.routes import bp as user_bp
    from AuthComponent.routes import bp as auth_bp
    from DataManager.routes import bp as data_bp
    from DeviceManager.routes import bp as device_bp
    from LogManager.routes import bp as log_bp 

    # 注册模块蓝图
    app.register_blueprint(user_bp)
    app.register_blueprint(device_bp)
    app.register_blueprint(data_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(log_bp)

    # 初始化MySQL数据库
    with app.app_context():
        # 先创建数据库
        conn = db.engine.connect()
        conn.execute(db.text("CREATE DATABASE IF NOT EXISTS AeroSentinel"))
        conn.close()

        # 创建所有表
        db.create_all()
        print("数据库初始化完成")

        # 初始化设备
        from DeviceManager.models import Device
        from config import Config

        # 检查并添加预设设备
        existing_devices = Device.query.all()
        existing_ids = {device.name for device in existing_devices}

        for device_id, device_key in Config.DEVICES.items():
            if device_id not in existing_ids:
                new_device = Device(name=device_id, secret=device_key)
                db.session.add(new_device)

        db.session.commit()
        print("设备初始化完成")

    app.run(
        host="0.0.0.0",   # , ssl_context=("aerosentinel.top.pem", "aerosentinel.top.key")
    )
